package sistem.management.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

public class ListaMaterialeMedic extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userEmail = req.getParameter("emaildoctor");
		System.out.println("Se cauta materiale pentru: "+ userEmail);
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Query query = new Query("material");
		List<Entity> materiale = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
		System.out.println("Sunt "+materiale.size()+ " materiale in total din care");
		List<Entity> materialeMedic = new ArrayList<Entity>();
		if (materiale != null) {
			for (Entity material : materiale) {
				if (material.getProperty("emaildoctor").equals(userEmail)) {
					materialeMedic.add(material);
				}
			}
			System.out.println(materialeMedic.size()+" apartin lui "+ userEmail);
		}
		JSONArray jsonArray = new JSONArray();
		if (materialeMedic.size() > 0) {
			for (Entity material : materialeMedic) {
				JSONObject json = new JSONObject();
				try {
					json.put("denumire", material.getProperty("denumire"));
					json.put("cantitate", material.getProperty("cantitate"));
					json.put("emaildoctor", material.getProperty("emaildoctor"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				jsonArray.put(json);
			}
		}
		System.out.println(jsonArray.toString());
		resp.getWriter().print(jsonArray.toString());
	}

}
